﻿using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MD5Hash;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Handler.Users
{
    public class CreateUserHandler : IRequestHandler<CreateUserCommand, APIResult<UserDTO>>
    {
        private readonly IRepository<Usermodel> userRepository;
        private readonly IRepository<Rolemodel> roleRepository;
        private readonly IRepository<Departmentmodel> depRepository;

        public CreateUserHandler(IRepository<Usermodel> userRepository,
            IRepository<Rolemodel> roleRepository,
            IRepository<Departmentmodel> depRepository)
        {
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;
            this.depRepository = depRepository;
        }

        public async Task<APIResult<UserDTO>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(request.Username) ||
                string.IsNullOrWhiteSpace(request.Realname))
            {
                return APIResult<UserDTO>.Faile("请完善必填信息");
            }

            var username = request.Username.Trim();

            bool exists = await userRepository.GetAll()
                .Where(u => u.IsDel == false && u.UserName == username)
                .AnyAsync();

            if (exists)
            {
                return APIResult<UserDTO>.Faile("账号已存在");
            }

            if (string.IsNullOrEmpty(request.Password))
            {
                request.Password = "123456";
            }

            var salt = Guid.NewGuid().ToString("N");
            var user = new Usermodel
            {
                Id = YitIdHelper.NextId(),
                UserName = username,
                UserCode = "UH0001",
                Password = request.Password.GetMD5WithSalt(salt),
                RealName = request.Realname.Trim(),
                Salt = salt,
                RoleId = request.RoleId,
                DepartmentId = request.DepartmentId,
                Phone = request.Phone,
                Email = request.Email,
                //Createdate = DateTime.Now,
                //Createname = "系统管理员", // TODO: 从当前登录用户获取
                IsDel = false
            };

            // 查询角色和部门信息并设置到用户
            var role = await roleRepository.GetByIdAsync(user.RoleId);
            var dep = await depRepository.GetByIdAsync(user.DepartmentId);

            user.RoleName = role?.RoleName;
            user.DepartmentName = dep?.DepartmentName;

            int rows = await userRepository.AddAsync(user);
            if (rows <= 0)
            {
                return APIResult<UserDTO>.Faile("创建用户失败");
            }

            var dto = new UserDTO
            {
                Id = user.Id,
                UserCode = user.UserCode,
                UserName = user.UserName,
                RealName = user.RealName,
                RoleId = user.RoleId,
                RoleName = user.RoleName ?? string.Empty,
                DepartmentId = user.DepartmentId,
                DepartmentName = user.DepartmentName ?? string.Empty,
                Phone = user.Phone,
                Email = user.Email
            };

            return APIResult<UserDTO>.Ok("创建用户成功", dto);
        }
    }
}
